package com.jeesite.modules.dp.service.column;

import com.google.common.base.Splitter;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.dp.dao.column.DpColumnDao;
import com.jeesite.modules.dp.entity.column.DpColumn;
import com.jeesite.modules.dp.entity.stocktmp.DpTmpjson;
import com.jeesite.modules.dp.service.stocktmp.DpTmpjsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据列管理Service
 *
 * @author hancing
 * @version 2024-12-05
 */
@Service
public class DpColumnService extends CrudService<DpColumnDao, DpColumn> {

    @Autowired
    private DpTmpjsonService dpTmpjsonService;

    /**
     * 获取单条数据
     *
     * @param dpColumn
     * @return
     */
    @Override
    public DpColumn get(DpColumn dpColumn) {
        return super.get(dpColumn);
    }

    /**
     * 查询分页数据
     *
     * @param dpColumn 查询条件
     * @param dpColumn page 分页对象
     * @return
     */
    @Override
    public Page<DpColumn> findPage(DpColumn dpColumn) {
        return super.findPage(dpColumn);
    }

    /**
     * 查询列表数据
     *
     * @param dpColumn
     * @return
     */
    @Override
    public List<DpColumn> findList(DpColumn dpColumn) {
        return super.findList(dpColumn);
    }

    /**
     * 查询所有可见的作为指标的column
     *
     * @return 查询结果
     */
    public List<DpColumn> findAllVisibleZbList() {
        DpColumn dpColumn = new DpColumn();
        dpColumn.setIszb("1");
        dpColumn.setVisbilezb("1");
        return findList(dpColumn);
    }

    public List<Map<String, String>> getCompareZbList(DpColumn column, List<DpColumn> zblist) {
        Map<String, DpColumn> columnMap = zblist.stream()
                .collect(Collectors.toMap(DpColumn::getColumnKey, item -> item));
        String zbcompare = column.getZbcompare();
        List<Map<String, String>> compareList = new ArrayList<>();
        if (!StringUtils.isBlank(zbcompare)) {
            Splitter.on(",").splitToList(zbcompare)
                    .forEach(item -> {
                        Map<String, String> cm = new HashMap<>();
                        if (columnMap.containsKey(item)) {
                            cm.put("label", columnMap.get(item).getColumnName());
                            cm.put("value", columnMap.get(item).getColumnDataindex());
                            compareList.add(cm);
                        }
                    });
        }
        return compareList;
    }

    /**
     * 查询所有的字段
     *
     * @return iscol=1代表是字段
     */
    public List<DpColumn> findAllColList() {
        DpColumn c = new DpColumn();
        c.setStatus("0");
        c.setIscol("1");
        return findList(c);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param dpColumn
     */
    @Override
    @Transactional
    public void save(DpColumn dpColumn) {
        super.save(dpColumn);
    }

    /**
     * 更新状态
     *
     * @param dpColumn
     */
    @Override
    @Transactional
    public void updateStatus(DpColumn dpColumn) {
        super.updateStatus(dpColumn);
    }

    private void dpColumnSortBySortNo(List<DpColumn> list) {
        list.forEach(item -> {
            if (item.getZbsortno() == null || item.getZbsortno().trim().isEmpty()) {
                item.setZbsortno("10000");
            }
        });
        list.sort((o1, o2) -> {
            int s1 = Integer.parseInt(o1.getZbsortno());
            int s2 = Integer.parseInt(o2.getZbsortno());
            return Integer.compare(s1, s2);
        });
    }

    /**
     * 删除数据
     *
     * @param dpColumn
     */
    @Override
    @Transactional
    public void delete(DpColumn dpColumn) {
        super.delete(dpColumn);
    }

    /**
     * 构建指标map
     *
     * @param c          column
     * @param compareMap x
     */
    private Map<String, Object> buildZbMapFromColumn(DpColumn c, Map<String, Map<String, Object>> compareMap) {
        Map<String, Object> map = new HashMap<>();
        map.put("zbkey", c.getColumnKey());
        map.put("zbname", c.getColumnName());

        // 组装比对列的数据列表
        List<Map<String, Object>> compareList = new ArrayList<>();

        if (!StringUtils.isEmpty(c.getZbcompare())) {
            Splitter.on(",").splitToList(c.getZbcompare())
                    .forEach(item -> compareList.add(compareMap.get(item)));
        }
        if (!StringUtils.isEmpty(c.getComparetext())) {
            Map<String, Object> tmpmap = new HashMap<>();
            tmpmap.put("label", c.getComparetext());
            tmpmap.put("value", "-1");
            compareList.add(tmpmap);
        }

        map.put("zbcompareList", compareList);
        map.put("valuetype", c.getValuetype());
        map.put("zbsearchunit", c.getZbsearchunit());
        map.put("amountunit", c.getAmountunit());
        map.put("zbcomparefuhao", "0");// 符号
        map.put("zbbeilv", "1"); // 倍率
        map.put("zbcomparetype", "0"); // 类型，选择的列还是手动输入 0是选择，1是输入
        map.put("zbcomparevalue", ""); // 类型值
        map.put("zbcompareinputalt", ""); // 类型值
        map.put("tmpid", null);
        map.put("sortno", StringUtils.isEmpty(c.getZbsortno()) ? -1 : Integer.parseInt(c.getZbsortno()));
        if (StringUtils.isEmpty(c.getZbcompare()) && StringUtils.isEmpty(c.getComparetext())) {
            map.put("zbcomparetype", "1");
        }
        map.put("cancompareList", !compareList.isEmpty() ? "1" : "0");

        return map;
    }

    /**
     * 构建模板指标
     *
     * @param tmpjson 模板json
     * @return 指标
     */
    private Map<String, Object> buildZbMapFromTmpJson(DpTmpjson tmpjson) {
        Map<String, Object> map = new HashMap<>();
        map.put("zbkey", tmpjson.getTmpname());
        map.put("zbname", tmpjson.getTmpname());
        map.put("zbcompareList", new ArrayList<>());
        map.put("valuetype", "BOOL");
        map.put("zbsearchunit", "");
        map.put("amountunit", "");
        map.put("zbcomparefuhao", "0");// 符号
        map.put("zbbeilv", "1"); // 倍率
        map.put("zbcomparetype", "0"); // 类型，选择的列还是手动输入 0是选择，1是输入
        map.put("zbcomparevalue", ""); // 类型值
        map.put("zbcompareinputalt", ""); // 类型值
        map.put("tmpid", tmpjson.getId());
        map.put("sortno", StringUtils.isEmpty(tmpjson.getZbsortno()) ? -1 : Integer.parseInt(tmpjson.getZbsortno()));
        return map;
    }

    /**
     * 查询筛选器的指标
     *
     * @return key: 指标类型
     */
    public Map<String, List<Map<String, Object>>> getZbList() {

        Map<String, List<Map<String, Object>>> zbtypeMapList = new HashMap<>();

        List<DpColumn> list = findAllVisibleZbList();

        dpColumnSortBySortNo(list);

        Map<String, List<DpTmpjson>> dpTmpMap = dpTmpjsonService.findAllZbList().stream()
                .collect(Collectors.groupingBy(DpTmpjson::getZbtype));

        // 先循环一次，获取key-name，方便给比对列赋值
        Map<String, Map<String, Object>> compareMap = new HashMap<>();
        for (DpColumn c : list) {
            Map<String, Object> tmpmap = new HashMap<>();
            tmpmap.put("label", c.getColumnName());
            tmpmap.put("value", c.getColumnKey());
            compareMap.put(c.getColumnKey(), tmpmap);
        }

        // 构建字段类型指标
        list.removeIf(item -> StringUtils.isEmpty(item.getZbtype()));
        Map<String, List<DpColumn>> columnsMap = list.stream().collect(Collectors.groupingBy(DpColumn::getZbtype));
        for (String zbType : columnsMap.keySet()) {
            List<DpColumn> columns = columnsMap.get(zbType);
            List<Map<String, Object>> ms = new ArrayList<>();
            for (DpColumn c : columns) {
                ms.add(buildZbMapFromColumn(c, compareMap));
            }
            zbtypeMapList.put(zbType, ms);
        }

        // 构建模板类型指标
        for (String zbType : dpTmpMap.keySet()) {
            List<DpTmpjson> tmps = dpTmpMap.get(zbType);
            List<Map<String, Object>> ms = zbtypeMapList.get(zbType) == null
                    ? new ArrayList<>() : zbtypeMapList.get(zbType);
            for (DpTmpjson tmpjson : tmps) {
                ms.add(buildZbMapFromTmpJson(tmpjson));
            }
            zbtypeMapList.put(zbType, ms);
        }

        // 指标排序
        for (String zbType : zbtypeMapList.keySet()) {
            List<Map<String, Object>> zbs = zbtypeMapList.get(zbType);
            zbs.sort((o1, o2) -> {
                Integer sort1 = (Integer) o1.get("sortno");
                Integer sort2 = (Integer) o2.get("sortno");
                return sort1.compareTo(sort2);
            });
        }

        return zbtypeMapList;
    }
}